package com.itfitness.viewmodeldemo;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    private TextView tv;
    private Button bt;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv = (TextView) findViewById(R.id.tv);
        bt = (Button) findViewById(R.id.bt);
        //绑定ViewModel
        MyViewModel myViewModel = new ViewModelProvider(this).get(MyViewModel.class);
        //获取LiveData
        MutableLiveData<String> name = myViewModel.getName();
        //对LiveData进行监听
        name.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                tv.setText(s);
            }
        });
        bt.setOnClickListener(v->{
            name.setValue("数据改变");
        });
    }
}